//
//  GMChangePasswordViewController.m
//  GuardMan
//
//  Created by steven on 2016/12/25.
//  Copyright © 2016年 steven. All rights reserved.
//

#import "GMNewPasswordViewController.h"
#import "GMAuthView.h"
#import "GMButton.h"
#import "GMAuthTextField.h"
#import "GMChangePasswordDataController.h"
#import "GMDebtorListViewController.h"
#import "GMMenuViewController.h"
#import "GMNavigationController.h"
#import <MMDrawerController/MMDrawerController.h>

@interface GMNewPasswordViewController ()

@property (nonatomic, strong)GMAuthView *authView;

@property (nonatomic, strong)GMChangePasswordDataController *changePasswordDataController;

@end

@implementation GMNewPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.changePasswordDataController = [[GMChangePasswordDataController alloc] init];
    
    [self setupContentView];
}

#pragma mark - setup content view
- (void)setupContentView {
    self.view.backgroundColor = [UIColor whiteColor];
    // set navigation title
    [self.navigationItem setTitle:@"重设密码"];
    
    // auth base view
    [self.view addSubview:self.authView];
    [self.authView autoPinEdgesToSuperviewEdges];
    
    // first password text field
    [self.authView addSubview:self.secondPasswordTextField];
    [self.secondPasswordTextField autoAlignAxisToSuperviewAxis:ALAxisVertical];
    [self.secondPasswordTextField autoAlignAxis:ALAxisHorizontal toSameAxisOfView:self.authView withOffset:-AUTH_TEXT_FIELD_HEIGHT];
    [self.secondPasswordTextField autoSetDimensionsToSize:CGSizeMake(self.view.frame.size.width*0.8,AUTH_TEXT_FIELD_HEIGHT)];
    
    // second password text field
    [self.authView addSubview:self.firstPasswdTextField];
    [self.firstPasswdTextField autoAlignAxisToSuperviewAxis:ALAxisVertical];
    [self.firstPasswdTextField autoPinEdge:ALEdgeBottom toEdge:ALEdgeTop ofView:self.secondPasswordTextField withOffset:-14];
    [self.firstPasswdTextField autoSetDimensionsToSize:CGSizeMake(self.view.frame.size.width*0.8, AUTH_TEXT_FIELD_HEIGHT)];
    
    // register button
    [self.authView addSubview:self.confirmChangeButton];
    [self.confirmChangeButton autoPinEdge:ALEdgeTop toEdge:ALEdgeBottom ofView:self.secondPasswordTextField withOffset:14];
    [self.confirmChangeButton autoAlignAxisToSuperviewAxis:ALAxisVertical];
    [self.confirmChangeButton autoSetDimensionsToSize:CGSizeMake(self.view.frame.size.width*0.8, AUTH_TEXT_FIELD_HEIGHT)];
}
#pragma mark - register button pressed
- (void)confirmChangeButtonPressed {
    [self.firstPasswdTextField resignFirstResponder];
    [self.secondPasswordTextField resignFirstResponder];
    
    NSString *password = self.firstPasswdTextField.text;
    NSString *secondPassword = self.secondPasswordTextField.text;
    if (password.length == 0) {
        NSLog(@"请输入密码");
        [self showAlertMessage:@"请输入密码"];
    } else if(secondPassword.length == 0) {
        [self showAlertMessage:@"请输入确认密码"];
    } else if (![password isEqualToString:secondPassword]) {
        [self showAlertMessage:@"密码不一致"];
    } else {
        // change password here
        NSDictionary *params = @{@"phone_number":self.phoneNo, @"newPassword":password, @"verifyCode":self.verificationCode};
        [self.changePasswordDataController changePasswordWhenForgotWithParams:params callback:^(NSString *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (error == nil) {
                    [self renderSuccessView];
                } else {
                    [self showAlertMessage:error];
                }
            });
        }];
    }
}

#pragma mark - render success view
- (void)renderSuccessView {
    NSDictionary *dict = self.changePasswordDataController.response[@"data"];
    NSString *token = dict[@"token"];
    NSDictionary *userDict = dict[@"user"];
    NSString *userId = [userDict[@"id"] stringValue];
    NSString *name = userDict[@"name"];
    NSString *headImg = userDict[@"headImg"];
    NSString *type = userDict[@"type"];
    NSString *vip = userDict[@"vip"];
    NSString *mobile = userDict[@"account"];
    NSString *recommend = userDict[@"recommend"];

    NSLog(@"Change forgot password succeed\nid:%@\nname:%@\nToken:%@", userId, name, token);

    // store user info
    [[NSUserDefaults standardUserDefaults] setObject:userId forKey:@"userId"];
    [[NSUserDefaults standardUserDefaults] setObject:name forKey:@"name"];
    [[NSUserDefaults standardUserDefaults] setObject:headImg forKey:@"headImageUrl"];
    [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"token"];
    [[NSUserDefaults standardUserDefaults] setObject:type forKey:@"type"];
    [[NSUserDefaults standardUserDefaults] setObject:vip forKey:@"vip"];
    [[NSUserDefaults standardUserDefaults] setObject:mobile forKey:@"mobile"];
    [[NSUserDefaults standardUserDefaults] setObject:recommend forKey:@"recommend"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    [self setupMainViewController];
}

#pragma mark - set up main viewController
- (void)setupMainViewController {
    GMDebtorListViewController *clientViewController = [[GMDebtorListViewController alloc] init];
    GMMenuViewController *menuViewController = [[GMMenuViewController alloc] init];

    GMNavigationController *centerNavigationVC = [[GMNavigationController alloc] initWithRootViewController:clientViewController];
    GMNavigationController *leftNavigationVC = [[GMNavigationController alloc] initWithRootViewController:menuViewController];

    MMDrawerController *drawerController = [[MMDrawerController alloc] initWithCenterViewController:centerNavigationVC leftDrawerViewController:leftNavigationVC];
    drawerController.openDrawerGestureModeMask = MMOpenDrawerGestureModeAll;
    drawerController.closeDrawerGestureModeMask = MMCloseDrawerGestureModeAll;

    drawerController.maximumLeftDrawerWidth = 200.0;

    [[[UIApplication sharedApplication] delegate] window].rootViewController = drawerController;
}

// Getter for authView
- (GMAuthView *)authView {
    if (!_authView) {
        _authView = [[GMAuthView alloc] init];
    }
    
    return _authView;
}

// Getter for first passwrod text field
- (GMAuthTextField *)firstPasswdTextField {
    if (!_firstPasswdTextField) {
        _firstPasswdTextField = [[GMAuthTextField alloc] init];
        _firstPasswdTextField.secureTextEntry = YES;
        _firstPasswdTextField.placeholder = @"新密码";
    }
    
    return _firstPasswdTextField;
}

// Getter for second passwrod text field
- (GMAuthTextField *)secondPasswordTextField {
    if (!_secondPasswordTextField) {
        _secondPasswordTextField = [[GMAuthTextField alloc] init];
        _secondPasswordTextField.secureTextEntry = YES;
        _secondPasswordTextField.placeholder = @"确认新密码";
    }
    
    return _secondPasswordTextField;
}

// Getter for register button
- (GMButton *)confirmChangeButton {
    if (!_confirmChangeButton) {
        _confirmChangeButton = [[GMButton alloc] init];
        [_confirmChangeButton setTitle:@"确认提交" forState:UIControlStateNormal];
        [_confirmChangeButton addTarget:self action:@selector(confirmChangeButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _confirmChangeButton;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
